﻿using DzInfo.Tools;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace DzInfo.FormPlugIn.GXD
{
    [Description("国信达:采购订单明细行关闭时，自动结案上游委外订单对应明细行"), HotUpdate]
    public class PurMRPClose : AbstractDynamicFormPlugIn
    {
        public override void AfterEntryBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterEntryBarItemClick(e);
            if (e.BarItemKey.EqualsIgnoreCase("POSW_tbButton"))
            {
                var entity = this.View.BillBusinessInfo.GetEntity("FPOOrderEntry");
                var sel = this.View.Model.GetEntryCurrentRowIndex("FPOOrderEntry");
                var eObj = this.View.Model.GetEntityDataObject(entity);
                if (eObj != null)
                {
                    var selObj = eObj[sel];
                    int eid = Convert.ToInt32(selObj["Id"]);
                    object pkEntryIds = Getwweid(eid);
                    List<object> pkes = new List<object>();
                    pkes.Add(pkEntryIds);
                    if (!pkEntryIds.IsNullOrEmptyOrWhiteSpace())
                    {
                        string data = KDApi.ExecuteParameter("", "", pkes.ToArray());
                        var data2 = new
                        {
                            PkEntryIds = pkes.ToArray()
                        };
                        data = JsonConvert.SerializeObject(data2);
                        var res = KDApi.Execute(this.Context, KdFomId.SUB_SUBREQORDER.ToString(), "ToClose", data);
                    }
                }
            }
        }
        //public override void EntryBarItemClick(BarItemClickEventArgs e)
        //{
        //    base.EntryBarItemClick(e);
        //}

        private object Getwweid(int eid)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T4.FID,T3.FENTRYID
            FROM T_PUR_POORDER T0
                 JOIN T_PUR_POORDERENTRY T1 ON T1.FID = T0.FID
                 JOIN T_PUR_POORDERENTRY_LK T2 ON T2.FENTRYID = T1.FENTRYID
                 JOIN T_SUB_REQORDERENTRY T3 ON T3.FID = T2.FSBILLID
                                                AND T3.FENTRYID = T2.FSID
                 JOIN T_SUB_REQORDER T4 ON T4.FID = T3.FID
            WHERE T1.FENTRYID={0} ", eid);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                var par = new
                {
                    Id = doc[0][0].ToString(),
                    EntryIds = doc[0][1].ToString()
                };
                return par;
            }
            return null;
        }
    }
}
